package com.yan.config;

import at.pollux.thymeleaf.shiro.dialect.ShiroDialect;
import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.LinkedHashMap;
import java.util.Map;

@Configuration  //config配置类
public class shiroConfig {

    //存放请求
    @Bean
    public ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier("securityManager") DefaultSecurityManager defaultSecurityManager) {
        ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean();
        bean.setSecurityManager(defaultSecurityManager);

        //添加 Shiro 的内置过滤器=======================
        /*
            anon : 无需认证，就可以访问
            authc : 必须认证，才能访问
            user : 必须拥有 “记住我”功能才能用
            perms : 拥有对某个资源的权限才能访问
            role : 拥有某个角色权限才能访问
         */
        Map<String, String> filter = new LinkedHashMap<>();

        //授权
        filter.put("/user/add", "perms[user:add]");
        filter.put("/user/update", "perms[user:update]");

        //设置了哪些路径必须认证
//        filter.put("/user/add","authc");
//        filter.put("/user/update","authc");
        filter.put("/user/*", "authc");
        bean.setFilterChainDefinitionMap(filter); //设置权限

        //无权限就去登录页面 此处指定了登录的页面
        bean.setLoginUrl("/toLogin");
        bean.setUnauthorizedUrl("/noauth");
        return bean;
    }


    //DefaultSecurityManagerc     和下面就绑定了
    @Bean(name = "securityManager")
    public DefaultWebSecurityManager getDefaultSecurityManager(@Qualifier("userRealm") UserRealm userRealm) {
        //DefaultWebSecurityManager 注意规范
        DefaultWebSecurityManager defaultSecurityManager = new DefaultWebSecurityManager();
        //关联UserRealm
        defaultSecurityManager.setRealm(userRealm);


        return defaultSecurityManager;

    }


    //创建 realm 对象   用户过滤
    @Bean //注入到bean
    public UserRealm userRealm() {
        return new UserRealm();
    }



    // Shiro 在 html 页面上方言配置
        //用来整合shiro  thymeleaf
    @Bean(name="shiroDialect")
    public ShiroDialect shiroDialect(){
        return new ShiroDialect();
    }
}
